package com.igrowing.easyRpc.tolerant;

import com.igrowing.easyRpc.loadbalancer.LoadBalancer;
import com.igrowing.easyRpc.loadbalancer.LoadBalancerFactory;
import com.igrowing.easyRpc.loadbalancer.LoadBalancerKeys;
import com.igrowing.easyRpc.model.RpcRequest;
import com.igrowing.easyRpc.model.RpcResponse;
import com.igrowing.easyRpc.model.ServiceMetaInfo;
import com.igrowing.easyRpc.server.tcp.VertxTcpClient;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Slf4j
public class FailOverTolerantStrategy implements TolerantStrategy {

    @Override
    public RpcResponse doTolerant(Map<String, Object> context, Exception e) {
        // todo 可自行扩展，获取其他服务节点并调用
        List<ServiceMetaInfo> list =(List<ServiceMetaInfo>) context.get("serviceList");
        RpcRequest rpcRequest = (RpcRequest) context.get("rpcRequest");
        LoadBalancer loadBalancer = LoadBalancerFactory.getInstance(LoadBalancerKeys.ROUND_ROBIN);
        ServiceMetaInfo serviceMetaInfo = loadBalancer.select(context, list);
        RpcResponse rpcResponse = null;
        try {
            RpcResponse response = VertxTcpClient.doRequest(rpcRequest, serviceMetaInfo);
        } catch (Exception e1) {
            e1.printStackTrace();
            throw new RuntimeException("服务重试失败,系统内部错误,请稍后再试");
        }
        return rpcResponse;
    }
}